package com.easyadmin.pro.tool;

import com.easyadmin.pro.common.constants.TokenConstant;
import com.easyadmin.pro.common.enums.HttpCodeEnum;
import com.easyadmin.pro.common.exception.EasyAdminProBaseException;
import com.easyadmin.pro.modules.sys.entity.UserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

/**
 * packageName com.easyadmin.pro.tool
 *
 * @author 骑着蚂蚁去上天
 * @version JDK 17
 * @className TokenUtils
 * @date 2024/4/1
 * @description token工具类
 */
@Slf4j
public class TokenUtils {

    /**
     * 创建Token
     * @param userEntity
     * @return
     */
    public static String create(UserEntity userEntity){
        return  Jwts.builder()
                .setId(userEntity.getId().toString())
                .setSubject(userEntity.getUserName())
                .setIssuedAt(new Date())
                .setIssuer(TokenConstant.ISSUER)
                .signWith(SignatureAlgorithm.HS512, TokenConstant.SECRET)
                .compact();
    }

    /**
     * 解析 Token
     *
     * @param token Token
     * */
    public static Claims parse(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(TokenConstant.SECRET)
                    .parseClaimsJws(token).getBody();
        }catch (Exception e){
            log.error("token 解析异常：{}", e);
        }
        return claims;
    }
}